import Vue from 'vue'
import Vuex from 'vuex'
import ws from '@/socket/socket'

let state = {
  // 服务器地址
  server: 'http://192.168.85.129:9527',
  // 用户信息
  userinfo: {username: '', uuid: 0},
  // 在线列表
  onLineList: [],
  // 当前窗口好友 在线列表的Key
  currentWindowObject: null,
  currentWindowUuid: 0,
  // 聊天记录
  chatHistory: {},
  // 好友列表搜索
  onLineSearch: '',
  // 服务器错误消息
  serverError: '',
  // 群聊
  groupList: [
    {
      gid: 1,
      type: 'group',
      name: '群聊-所有人',
      userList: 'all',
      chatHistory: [],
      newMsg: false
    }
  ],
  // 当前窗口为群聊
  currentWindowIsGroup: false
}

let mutations = {
  set_userinfo (state, userinfo) {
    state.userinfo = userinfo
    syncLocalStroage('userinfo')
  },
  set_on_line_list (state, onLineList) {
    state.onLineList = onLineList
    syncLocalStroage('onLineList')
  },
  set_current_window_obj (state, data) {
    state.currentWindowIsGroup = data.group
    state.currentWindowObject = data.key
    if (data.group) {
      state.groupList[state.currentWindowObject].newMsg = false
    } else {
      state.onLineList[state.currentWindowObject].newMsg = false
      state.currentWindowUuid = state.onLineList[state.currentWindowObject].uuid
    }
  },
  append_chat_history (state, data) {
    let uuid = 0
    if (data.event === undefined) {
      uuid = state.currentWindowUuid
    } else {
      uuid = data.from.uuid
      if (uuid !== state.currentWindowUuid) {
        // 未读消息提醒
        state.onLineList.forEach((val, key) => {
          if (val.uuid === uuid) {
            state.onLineList[key].newMsg = true
          }
        })
      }
    }
    if (state.chatHistory[uuid] === undefined) {
      state.chatHistory[uuid] = []
    }
    state.chatHistory[uuid].push(data)
    state.chatHistory = Object.assign({}, state.chatHistory)
    // 在线列表重新排序
    let temp = []
    state.onLineList.forEach((val) => {
      if (val.uuid === uuid) {
        temp.unshift(val)
      } else {
        temp.push(val)
      }
    })
    state.onLineList = temp
  },
  set_on_line_search (state, search) {
    state.onLineSearch = search
  },
  set_server_error (state, serverError) {
    state.serverError = serverError
  },
  append_group_chat_history (state, data) {
    state.groupList.forEach((val, key) => {
      if (val.gid === data.gid) {
        if (data.event === 'msg') {
          if (state.currentWindowIsGroup) {
            if (key === state.currentWindowObject) {
              state.groupList[key].newMsg = false
            } else {
              state.groupList[key].newMsg = true
            }
          } else {
            state.groupList[key].newMsg = true
          }
        }
        state.groupList[key].chatHistory.push(data)
      }
    })
  }
}

let actions = {
  login (ctx, userinfo) {
    ctx.commit('set_userinfo', userinfo)
    ws.open(() => {
      ws.send({
        event: 'login',
        from: state.userinfo,
        data: state.userinfo.username + '上线了！'
      })
    }, (info) => {
      ctx.commit('set_server_error', info)
    })
    ws.message((data) => {
      let temp = null
      switch (data.event) {
        case 'online':
          temp = data.data
          break
        case 'login':
          temp = state.onLineList
          temp.unshift(data.from)
          break
        case 'logout':
          temp = state.onLineList.filter((val) => {
            return val.uuid !== data.from.uuid
          })
          break
        case 'msg':
          if (data.gid === undefined) {
            ctx.commit('append_chat_history', data)
          } else {
            ctx.commit('append_group_chat_history', data)
          }
          break
      }
      if (temp !== null) {
        ctx.commit('set_on_line_list', temp)
      }
    })
  },
  logout (ctx) {
    ctx.commit('set_userinfo', {username: '', uuid: 0})
    ctx.commit('set_on_line_list', [])
    ws.close()
  },
  tapChat (ctx, data) {
    ctx.commit('set_current_window_obj', data)
  },
  send (ctx, data) {
    let content = data.content
    let type = data.type === undefined ? '' : data.type
    let res = {
      data: content,
      from: state.userinfo,
      type
    }
    if (state.currentWindowIsGroup) {
      res.to = -state.userinfo.uuid
      res.gid = state.groupList[state.currentWindowObject].gid
      ctx.commit('append_group_chat_history', res)
    } else {
      res.to = state.currentWindowUuid
      ctx.commit('append_chat_history', res)
    }
    ws.send(res)
  },
  search (ctx, search) {
    ctx.commit('set_on_line_search', search)
  }
}

function syncLocalStroage (key) {
  try {
    localStorage[key] = JSON.stringify(state[key])
  } catch (e) {}
}

try {
  let userinfo = JSON.parse(localStorage.userinfo)
  if (userinfo.uuid !== 0) {
    state.userinfo = userinfo
  }
} catch (e) {}

Vue.use(Vuex)
export default new Vuex.Store({
  state,
  actions,
  mutations
})
